package com.sh.secondhand;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.sh.Application.BaseApplication;
import com.sh.struts.DeliveryAddressData;
import com.sh.struts.ProductData;
import com.sh.utils.BackgroundManagerUtils;
import com.sh.utils.Utils;

import java.util.Map;

public class ReadyCreateOrderActivity extends AppCompatActivity implements View.OnClickListener {
    private static final Integer DELIVERY_REQUEST_CODE = 1600;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.product_img)
    SimpleDraweeView productImg;
    @BindView(R.id.product_title)
    TextView productTitle;
    @BindView(R.id.product_price)
    TextView productPrice;
    @BindView(R.id.product_buy_price)
    TextView productBuyPrice;
    @BindView(R.id.delivery_address_area)
    LinearLayout deliveryAddressArea;
    @BindView(R.id.name_mobile_area)
    TextView nameMobileArea;
    @BindView(R.id.full_address_area)
    TextView fullAddressArea;
    @BindView(R.id.express_fee_area)
    TextView expressFeeArea;
    @BindView(R.id.order_price_area)
    TextView orderPriceArea;
    @BindView(R.id.sure_area)
    TextView sureArea;

    private Intent intent;
    private DeliveryAddressData deliveryAddressData;
    private ProductData productData;
    private SweetAlertDialog pdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ready_create_order);
        ButterKnife.bind(this);
        toolbar.setTitle("");
        pdialog = new SweetAlertDialog(ReadyCreateOrderActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        intent = getIntent();
        productData = (ProductData) intent.getSerializableExtra("product_data");
        initProductInfo(productData);
        new DeliveryAddressInfo().execute((Void) null);
    }

    @SuppressLint("ResourceAsColor")
    private void initProductInfo(ProductData productData) {
        if (productData == null) {
            return;
        }
        Uri showImgUri = Uri.parse(productData.img);
        productImg.setImageURI(showImgUri);
        productTitle.setText(productData.title);
        productPrice.setText(String.format("￥%s", productData.price));
        if (productData.buyPrice != 0) {
            productBuyPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
            productBuyPrice.getPaint().setColor(R.color.text_color_gray);
            productBuyPrice.setText(String.format("￥%s", productData.buyPrice));
        }
        expressFeeArea.setText(String.format("￥%s", productData.expressFee));
        String str = String.format("%s<font color='#ff4444'>￥%s</font>", "实付款：", productData.price + productData.expressFee);
        orderPriceArea.setText(Html.fromHtml(str));
    }

    private void initDeliveryInfo(DeliveryAddressData deliveryAddressData) {
        nameMobileArea.setText(String.format("%s%s", deliveryAddressData.name, deliveryAddressData.mobile));
        fullAddressArea.setText(deliveryAddressData.getRealFullAddress());
    }

    @OnClick({R.id.delivery_address_area, R.id.sure_area})
    @Override
    public void onClick(View v) {
        Integer viewId = v.getId();
        switch (viewId) {
            case R.id.delivery_address_area: {
                if (Utils.checkLogin()) {
                    Intent intent = new Intent(ReadyCreateOrderActivity.this, DeliveryAddressManagerActivity.class);
                    startActivityForResult(intent, DELIVERY_REQUEST_CODE);
                }
                break;
            }
            case R.id.sure_area: {
                new SweetAlertDialog(ReadyCreateOrderActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("确定购买？")
                        .setCancelText("取消")
                        .setConfirmText("确定")
                        .showCancelButton(true)
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.cancel();
                            }
                        })
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                                new OrderCreate(deliveryAddressData == null ? 0 : deliveryAddressData.id, productData == null ? 0 : productData.productId).execute((Void) null);
                            }
                        })
                        .show();
                break;
            }
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == DELIVERY_REQUEST_CODE) {
                DeliveryAddressData deliveryAddressData = (DeliveryAddressData) data.getSerializableExtra("delivery_address");
                if (deliveryAddressData != null) {
                    this.deliveryAddressData = deliveryAddressData;
                    initDeliveryInfo(this.deliveryAddressData);
                }
            }
        }
    }

    public class DeliveryAddressInfo extends AsyncTask<Void, Void, Void> {
        public Integer userId;

        public DeliveryAddressInfo() {
            if (Utils.checkLogin()) {
                userId = BaseApplication.getLoginInfo().getUserId();
            }
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Map<String, String> resMap = BackgroundManagerUtils.getDefaultDeliveryAddress(userId);
            deliveryAddressData = new DeliveryAddressData(resMap);
            runOnUiThread(() -> {
                initDeliveryInfo(deliveryAddressData);
            });
            return null;
        }
    }

    public class OrderCreate extends AsyncTask<Void, Void, Void> {
        public Integer userId;
        public Integer deliveryAddressId;
        public Integer productId;

        public OrderCreate(Integer deliveryAddressId, Integer productId) {
            if (Utils.checkLogin()) {
                userId = BaseApplication.getLoginInfo().getUserId();
            }
            this.deliveryAddressId = deliveryAddressId;
            this.productId = productId;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            runOnUiThread(() -> {
                pdialog.show();
            });
            Map<String, String> resMap = BackgroundManagerUtils.createOrder(userId, productId, deliveryAddressId);
            runOnUiThread(() -> {
                pdialog.dismiss();
                if (resMap == null || "error".equals(resMap.get("status"))) {
                    new SweetAlertDialog(ReadyCreateOrderActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("错误")
                            .setContentText("购买失败！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                } else if (resMap == null || "saled".equals(resMap.get("status"))) {
                    new SweetAlertDialog(ReadyCreateOrderActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("错误")
                            .setContentText("商品已售出！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            })
                            .show();
                } else {
                    new SweetAlertDialog(ReadyCreateOrderActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("成功")
                            .setContentText("购买成功！")
                            .setConfirmText("好的")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                    Intent intent = new Intent(ReadyCreateOrderActivity.this, MainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                }
                            })
                            .show();
                }
            });
            return null;
        }
    }

    /**
     * 在子线程里需要使用Toast
     *
     * @param context
     * @param message
     */
    public void showToastOnThread(Context context, String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
